package com.qasystem.qa.core.controller;

import com.qasystem.qa.core.base.Result;
import com.qasystem.qa.core.service.LoginService;
import com.qasystem.qa.core.utils.Results;
import com.qasystem.qa.core.utils.UUIDCreater;
import com.qasystem.qa.system.entity.User;
import com.qasystem.qa.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

@Controller
public class UserLoginController {
    @Autowired
    private LoginService loginService;
    @Autowired
    private UserService userService;

    @GetMapping("/login")
    public String loginUser() {
        return "login";
    }

    @GetMapping("/register")
    public String registerUser() {
        return "register";
    }

    @GetMapping("/index")
    public String index(){
        return "index";
    }

    @GetMapping("/loginAction")
    @ResponseBody
    public Result login (String username, String password, String verifyCode,HttpServletRequest request, HttpServletResponse response) {
//        Result result = loginService.login(username, password, response);
        return loginService.login(username, password, request,response);

    }

    @GetMapping("/logout")
    @ResponseBody
    public Result logout (HttpServletRequest request, HttpServletResponse response) throws Exception {
        return loginService.logout(request, response);
    }

    @GetMapping ("/registerAction")
    @ResponseBody
    public Result register (String username, String password, String repassword, HttpServletRequest request, HttpServletResponse response) {
        Result result = new Result();
        result.setSuccess(false);
        result.setMsg("注册失败");
        if (username != null && password != null && repassword != null) {
            if (!Objects.equals(password, repassword)) {
                return Results.failure("密码和确认密码不一致");
            }

            User register_user = new User(username, password);
            List<User> user = userService.select(register_user);
            if (!user.isEmpty()) {
                return Results.failure("用户已经被注册");
            }
            String userId = UUIDCreater.createUserId();
            register_user.setUserid(userId);
            //System.out.println(user.get(0).getUsername());
            userService.insert(register_user);
            result = loginService.login(username, password, request, response);
            result.setMsg("用户注册成功");
        }
        return result;
    }

}
